//
//  HMAllOrdersViewController.swift
//  ServiceHelper
//
//  Created by Xuedan on 15/11/3.
//  Copyright © 2015年 Stan Wu. All rights reserved.
//

import UIKit
import AVFoundation

class HMAllOrdersViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,SHOrderDetailDelegate,UISearchBarDelegate,SHAllOrdersDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,SHOrderNotificationDetailDelegate,SWImageViewDelegate,UIAlertViewDelegate,UITextFieldDelegate{
    
    var tvList: UITableView!
    var tvListPerson: UITableView!
    var vDetail: SHOrderDetailView!
    var vAllOrders: HMAllOrdersView!
//    var vSelectPerson :SHSelectTakeCarPersonVIew
     var vNotificationDetail: SHOrdersNotificationDetailView!
    var aryList = NSMutableArray()
    var aryPersonList = NSMutableArray()
    var selectedOrder: NSDictionary?
    var dicSelectedPersonInfo: NSDictionary?
    
    var dicOrderDetail: NSDictionary?
    var refreshController: UIRefreshControl!
    var dCurrentPage = 1
    lazy var searchBar :UISearchBar = UISearchBar(frame: CGRectMake(0, 0, 300,20))
    var order_status: String = "0"
    var notice_status: String = "0"
//    var strNavTitle = NSString()
    var realkey : NSString?
    var imgvPhoto :UIImageView!
    var pop: UIPopoverController!
    var vPay : UIView!
    var vMark : UIView!
    var vMarkSearch : UIView!
    var vMarkPerson:UIView!
    var btnHide: UIButton!
    var photoCount = Int()
    var aryPhotos = NSMutableArray()
    var aryPhotosURI = NSMutableArray()
    var tfPrice : UITextField!
    var isSelectedPerson: Bool!
    var isFromNotification: Bool?
    var isFromSearchOrder: Bool?
    var isFromWaitingOrder: Bool?
    var IndexSelected : NSNumber!
    var isSelectedNotice: Bool!
    var IndexNoticeSelected : NSNumber!
    var isStartLoadingMore: Bool?
    var vSearchOrderView : UIView!
    var btnShowSearch :UIButton!
    
    var btnHidePusPay :UIButton!
    var imgvSearchBG :UIImageView!
    var aryButtonStatus :NSMutableArray!
    
    var imagePicker : UIImagePickerController!
    var strPrice : NSString!
    
   
    var strNavTitle: NSString?{
        didSet{
            
//            strShowType = strType
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.addBGColor()
        // Do any additional setup after loading the view.
        
        self.setNavBGImage()
        
        aryButtonStatus = [false ,false,false,false,false,false,false,false]
//        aryButtonStatus = NSMutableArray.addObjectsFromArray(ary)
        
        
        isStartLoadingMore = false
        tvList = UITableView(frame: CGRectMake(0, 0, 320, 768-44-20))
        tvList.backgroundColor = UIColor.clearColor()
        tvList.delegate = self
        tvList.dataSource = self
        tvList.separatorStyle = .None
        self.view.addSubview(tvList)
        
        
        if isFromNotification == true{
            self.createNotificationDetailView()

        }else{
            
            if isFromWaitingOrder == true{
                order_status = "1,3,4,7,8,9,10,14"
            }
            searchBar.placeholder = "搜索"
            searchBar.delegate = self
            let rightNavBarButton = UIBarButtonItem(customView: searchBar)
            self.navigationItem.rightBarButtonItem = rightNavBarButton
            self.createOrderDetailView()
        }
        
        
        
        vDetail = SHOrderDetailView(frame: CGRectMake(320, 0, 1024-320, 768))
        vDetail.backgroundColor = UIColor(red: 0.95, green: 0.96, blue: 0.97, alpha: 1)
        vDetail.layer.shadowColor = UIColor.blackColor().CGColor
        vDetail.layer.shadowRadius = 1
        vDetail.layer.shadowOffset = CGSizeMake(-2, 0)
        vDetail.layer.shadowOpacity = 0.1
        vDetail.delegate = self
        vDetail.hidden  = true
        self.view.addSubview(vDetail)
        
        
        
//        if isFromNotification == true {
//            vNotificationDetail.hidden = false
//            vAllOrders.hidden = true
//        }else if isFromSearchOrder == true{
//            vNotificationDetail.hidden = true
//            vAllOrders.hidden = false
//        }
//        else{
//            vNotificationDetail.hidden = true
//            vAllOrders.hidden = false
//        }
        
        vMarkSearch = UIView.init(frame: CGRectMake(0, 0, 320, 768))
        vMarkSearch.backgroundColor = UIColor.blackColor()
        vMarkSearch.alpha = 0.30
        self.view.addSubview(vMarkSearch)
        vMarkSearch.hidden = true

        imgvSearchBG = UIImageView.init(frame: CGRectMake(0, 50, 320, 360))
        imgvSearchBG.image = UIImage(named: "bg")
        imgvSearchBG.userInteractionEnabled = true
        self.view.addSubview(imgvSearchBG)
        imgvSearchBG.hidden = true
        
        
        var titles = "预约成功，预约已确认，待上门取车，正在服务中，待送车上门，待支付，待评价，已完成".componentsSeparatedByString("，")
        for i in 0 ..< titles.count{
            let col = i % 2
            let row = i / 2
            
            let btn = UIButton(type: .Custom)
            btn.setBackgroundImage(UIImage(named: "nor"), forState: .Normal)
            btn.setBackgroundImage(UIImage(named: "sel"), forState: .Selected)
            btn.sizeToFit()
            btn.frame = CGRectMake(20 + (CGFloat)(150*col), 30 + (CGFloat)(62*row), 130, 40) //CGRectMake(CGFloat(20+130*col), CGFloat(20+62.5*row), 130 , 40)
            btn.setTitle(titles[i], forState: .Normal)
            btn.titleLabel?.font = UIFont.boldSystemFontOfSize(17)
            btn.setTitleColor(UIColor.grayColor(), forState: .Normal)
            btn.setTitleColor(UIColor.whiteColor(), forState: .Selected)
            
            btn.setImage(UIImage(named: "right_icon"), forState: .Selected)
            btn.titleEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0)
            btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -160)
            btn.tag = 300+i
            btn.addTarget(self, action: #selector(HMAllOrdersViewController.searchClassedSelected(_:)), forControlEvents: .TouchUpInside)
            imgvSearchBG.addSubview(btn)

        }
        
        let btn = UIButton(type: .Custom)
        btn.setBackgroundImage(UIImage(named: "sel"), forState: .Normal)
        btn.sizeToFit()
        btn.frame = CGRectMake(55, 300, 210, 45)
        btn.setTitle("确定", forState: .Normal)
        btn.titleLabel?.font = UIFont.boldSystemFontOfSize(20)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.tag = 308
        btn.addTarget(self, action: #selector(HMAllOrdersViewController.searchClassedSelected(_:)), forControlEvents: .TouchUpInside)
        imgvSearchBG.addSubview(btn)

        
        let line = UIView(frame: CGRectMake(0, 275, 320 , 0.5))
        line.backgroundColor = UIColor(white: 0.88, alpha: 1)
        imgvSearchBG.addSubview(line)
        
        var myDelegate:AppDelegate
        myDelegate = (UIApplication.sharedApplication().delegate as? AppDelegate)!
        
        vMarkPerson = UIView.init(frame: CGRectMake(0,0,1024,768))
        vMarkPerson.backgroundColor = UIColor.blackColor()
        vMarkPerson.alpha = 0.5
        myDelegate.window?.addSubview(vMarkPerson)
        vMarkPerson.hidden = true
        
        btnHide = UIButton (type: UIButtonType.Custom)
        btnHide.frame = CGRectMake(0, 0, 1024, 768)
        btnHide.backgroundColor = UIColor.clearColor()
        myDelegate.window?.addSubview(btnHide)
        btnHide.addTarget(self, action: #selector(HMAllOrdersViewController.dismissShowViews), forControlEvents: .TouchUpInside)
        btnHide.hidden = true
        
        tvListPerson = UITableView(frame: CGRectMake(1024-270, 64, 270, 768-44-20))
        tvListPerson.backgroundColor = UIColor.whiteColor()
        tvListPerson.delegate = self
        tvListPerson.dataSource = self
        tvListPerson.separatorStyle = .None
        myDelegate.window?.addSubview(tvListPerson)
        tvListPerson.hidden = true
        
        
        
        let vFooterPerson = UIView.init(frame: CGRectMake(0, tvListPerson.frame.size.height-75, 270, 75))
        vFooterPerson.backgroundColor = UIColor.whiteColor()
        vFooterPerson.layer.shadowColor = UIColor.blackColor().CGColor
        vFooterPerson.layer.shadowRadius = 1
        vFooterPerson.layer.shadowOffset = CGSizeMake(-2, 0)
        vFooterPerson.layer.shadowOpacity = 0.1
        tvListPerson.addSubview(vFooterPerson);
        
        let btnSelectedPerson  = UIButton(type: UIButtonType.Custom)
        btnSelectedPerson.frame = CGRectMake(35, 15, 200, 45)
        btnSelectedPerson.backgroundColor = UIColor(red: 0.14, green: 0.50, blue: 0.78, alpha: 1)
        btnSelectedPerson.setTitle("确定", forState: UIControlState.Normal)
        btnSelectedPerson.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        vFooterPerson.addSubview(btnSelectedPerson)
        btnSelectedPerson.addTarget(self, action: #selector(HMAllOrdersViewController.btnSelectedPersonClicked), forControlEvents: .TouchUpInside)

//        tvListPerson.tableFooterView = vFooterPerson
        
        
        NSThread.detachNewThreadSelector(#selector(HMAllOrdersViewController.loadData), toTarget: self, withObject: nil)
        
        refreshController = UIRefreshControl()
        refreshController.addTarget(self, action: #selector(HMAllOrdersViewController.refreshChanged(_:)), forControlEvents: .ValueChanged)
        tvList.addSubview(refreshController)
        
//        self.hiddenTakeCarPerson()
        
//        NSNotificationCenter.defaultCenter().addObserver(self, selector: "refresh", name: "RefreshOrderList", object: nil)

    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func createNotificationDetailView(){
        vNotificationDetail = SHOrdersNotificationDetailView(frame: CGRectMake(320, 0, 1024-320, 768))
        vNotificationDetail.backgroundColor = UIColor.whiteColor()
        vNotificationDetail.strNew = strNavTitle
        vNotificationDetail.delegateNotification = self
        vNotificationDetail.strStatus = "1"
        self.view.addSubview(vNotificationDetail)
//        vNotificationDetail.hidden = true
    }
    
    func createOrderDetailView(){
        vAllOrders = nil
        vAllOrders = HMAllOrdersView(frame: CGRectMake(320, 0, 1024-320, 768))
        vAllOrders.backgroundColor = UIColor.whiteColor()
        vAllOrders.strNew = strNavTitle
        vAllOrders.layer.shadowColor = UIColor.blackColor().CGColor
        vAllOrders.layer.shadowRadius = 1
        vAllOrders.layer.shadowOffset = CGSizeMake(-2, 0)
        vAllOrders.layer.shadowOpacity = 0.1
        vAllOrders.allOrdersDelegate = self
        vAllOrders.strType = "1"
        if isFromNotification == true{
            vAllOrders.isFromNotification = true
            vAllOrders.strOrderId = vNotificationDetail.orderNotificationInfo?.objectForKey("order_id") as! String
        }
        self.view.addSubview(vAllOrders)
//        vAllOrders.hidden = true

    }
    
    
    
    func dismissShowViews(){
        self.view.endEditing(true)
        if tfPrice != nil{
            tfPrice.resignFirstResponder()
        }
        
        btnHide.hidden = true
        vMarkPerson.hidden = true
        tvListPerson.hidden = true
        if vMark != nil {
            vMark.hidden = true
        }
        
        if btnHidePusPay != nil{
             btnHidePusPay.hidden = true
        }
        
        if vPay != nil {
            vPay.hidden = true

        }
       
               self.aryPhotos.removeAllObjects()
        self.aryPhotosURI.removeAllObjects()
        photoCount = 0
    }
    
    func btnSelectedPersonClicked(){
        btnHide.hidden = true
        vMarkPerson.hidden = true
        tvListPerson.hidden = true
        
        if dicSelectedPersonInfo != nil {
            let strOrderStatus = vAllOrders.allOrdersInfo?.objectForKey("order_status")?.intValue
            let orderType = vAllOrders.allOrdersInfo?.objectForKey("pick_type") as! String!
            
            if strOrderStatus == 3{
                NSThread.detachNewThreadSelector(#selector(HMAllOrdersViewController.selectedGetCarPerson), toTarget: self, withObject: nil)
            }else  if strOrderStatus == 4{
                if orderType == "2"{
                    NSThread.detachNewThreadSelector(#selector(HMAllOrdersViewController.selectedSendCarPerson), toTarget: self, withObject: nil)
                }
                
                
            }else  if strOrderStatus == 1{
                NSThread.detachNewThreadSelector(#selector(HMAllOrdersViewController.selectedGetCarPerson), toTarget: self, withObject: nil)
            }

        }else{
            UIAlertView.show(nil, message: "请选择取车员", cancelButton: nil)
        }
        
    }
    
    //选中搜索
    func searchClassedSelected (sender:UIButton){
        
        if sender.tag != 308{
            let isSel  = aryButtonStatus[sender.tag-300].boolValue
            if isSel == false{
                sender.selected = true
                aryButtonStatus[sender.tag-300] = true
            }else{
                sender.selected = false
                aryButtonStatus[sender.tag-300] = false
            }

        }
        

        switch sender.tag{
        case 300:
            print(300)
            sender.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -165)
        case 301:
            print(301)
            sender.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -185)

        case 302:
            print(302)
            sender.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -185)
        case 303:
            print(303)
            sender.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -185)
        case 304:
            print(304)
            sender.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -185)
        case 305:
            print(305)
            sender.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -150)
        case 306:
            print(306)
            sender.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -150)
        case 307:
            print(307)
            sender.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -150)
        case 308:
            print(308)
            vMarkSearch.hidden = true
            imgvSearchBG.hidden = true
            btnShowSearch.selected = false
            
            self.changeOrderStatus()
            
        default:()
            
        }
        
    }
    
    
    func changeOrderStatus(){
        let ary = ["1","3","6","8","11","4,9","10","5"]
        let str = NSMutableString()
        for i in 0 ..< aryButtonStatus.count{
            let sel = aryButtonStatus.objectAtIndex(i).boolValue
            if sel == true{
                str.appendString(ary[i])
                str.appendString(",")
            }
        }
        
        
        order_status = str as String
        self.refresh()
    }

    
    func refreshChanged(sender: UIRefreshControl){
        self.refresh()
    }
    
    func refresh(){
        NSThread.detachNewThreadSelector(#selector(HMAllOrdersViewController.loadData), toTarget: self, withObject: nil)
    }
    
    func loadData(){
        autoreleasepool { () -> () in
            dCurrentPage = 1;
            
            if isFromNotification == true{
                let dict = SHDataProvider.getDealerNoticeList(["type":notice_status,"dealer_id":SHDataProvider.getDealerID()])
                let ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
                
                SWUtils.RunOnMainThread({ () -> Void in
                    if let orderList = ary{
                        self.aryList.removeAllObjects()
                        self.aryList = NSMutableArray(array: orderList)
                        
                        if orderList.count>0{
                            let formatter = NSDateFormatter()
                            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
                            let d = formatter.dateFromString(orderList[0].objectForKey("create_time") as! String)
                            if let dd = d{
                                NSUserDefaults.standardUserDefaults().setObject(dd, forKey: "LatestOrderTime")
                            }
                        }
                    }else{
                        self.aryList.removeAllObjects()
                    }
                    
                    self.tvList.reloadData()
                    self.refreshController.endRefreshing()
                    
                    if self.aryList.count>0{
                        self.tableView(self.tvList, didSelectRowAtIndexPath: NSIndexPath(forRow: 0, inSection: 0))
                    }else{
//                        self.vAllOrders.allOrdersInfo = nil
                        self.vNotificationDetail.orderNotificationInfo = nil
                    }
                    
                    
                })

            }else{
                
                let strSearchText :NSString = searchBar.text!
                if strSearchText.length <= 0 {
                    let dict = SHDataProvider.getDealerOrderList(["order_status":order_status,"dealer_id":SHDataProvider.getDealerID()])
                    
                    //            var dict = SHDataProvider.getDealerOrderList(["dealer_id":SHDataProvider.getDealerID()])
                    
                    let ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let orderList = ary{
                            self.aryList.removeAllObjects()
                            self.aryList = NSMutableArray(array: orderList)
                            
                            if orderList.count>0{
                                let formatter = NSDateFormatter()
                                formatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
                                let d = formatter.dateFromString(orderList[0].objectForKey("create_time") as! String)
                                if let dd = d{
                                    NSUserDefaults.standardUserDefaults().setObject(dd, forKey: "LatestOrderTime")
                                }
                            }
                        }else{
                            self.aryList.removeAllObjects()
                        }
                        
                        self.tvList.reloadData()
                        self.refreshController.endRefreshing()
                        
                        if self.aryList.count>0{
                            self.tableView(self.tvList, didSelectRowAtIndexPath: NSIndexPath(forRow: 0, inSection: 0))
                        }else{
//                            self.vDetail.orderInfo = nil
                            self.vAllOrders.allOrdersInfo = nil
                        }
                        
                        
                    })

                }else{
                     let dict = SHDataProvider.getDealerOrderList(["search_no":searchBar.text!,"account_type":"1","order_status":order_status,"dealer_id":SHDataProvider.getDealerID()])
                    let ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let orderList = ary{
                            self.aryList.removeAllObjects()
                            self.aryList = NSMutableArray(array: orderList)
                            
                            if orderList.count>0{
                                let formatter = NSDateFormatter()
                                formatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
                                let d = formatter.dateFromString(orderList[0].objectForKey("create_time") as! String)
                                if let dd = d{
                                    NSUserDefaults.standardUserDefaults().setObject(dd, forKey: "LatestOrderTime")
                                }
                            }
                        }else{
                            self.aryList.removeAllObjects()
                        }
                        
                        self.tvList.reloadData()
                        self.refreshController.endRefreshing()
                        
                        if self.aryList.count>0{
                            self.tableView(self.tvList, didSelectRowAtIndexPath: NSIndexPath(forRow: 0, inSection: 0))
                        }else{
//                            self.vDetail.orderInfo = nil
                            self.vAllOrders.allOrdersInfo = nil
                        }
                        
                        
                    })

                }
                
                
            }
            
        }
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
//        125 150
        if isFromNotification == true{
            if aryList.count >= 20 {
                let cunt =  aryList.count
                if (scrollView.contentOffset.y + scrollView.frame.size.height) >  (CGFloat)( 125 * cunt) {
                    let footview = UIView.init(frame: CGRectMake(0, 0, 320, 40))
                    footview.backgroundColor = UIColor(white: 0.9, alpha: 1)
                    
                    let activityIndicator = UIActivityIndicatorView.init()
                    activityIndicator.activityIndicatorViewStyle  = UIActivityIndicatorViewStyle.Gray
                    activityIndicator.center = CGPointMake(160, 20)
                    footview.addSubview(activityIndicator)
                    
                    activityIndicator.startAnimating()
                    tvList.tableFooterView = footview
                   
                    NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: Selector("delayLoadMoreData"), object: nil)
                    self.performSelector(#selector(HMAllOrdersViewController.loadMoreData), withObject: nil, afterDelay: 0.3)
                }
            }
        }else{
            if aryList.count >= 20 * self.dCurrentPage {
                if aryList.count >= 20  * self.dCurrentPage{
                    let cunt =  aryList.count
                    if (scrollView.contentOffset.y + scrollView.frame.size.height) >  (CGFloat)( 150 * cunt)+100 {
                        let footview = UIView.init(frame: CGRectMake(0, 0, 320, 40))
                        footview.backgroundColor = UIColor(white: 0.9, alpha: 1)
                        
                        let activityIndicator = UIActivityIndicatorView.init()
                        activityIndicator.activityIndicatorViewStyle  = UIActivityIndicatorViewStyle.Gray
                        activityIndicator.center = CGPointMake(160, 20)
                        footview.addSubview(activityIndicator)
                        
                        activityIndicator.startAnimating()
                        tvList.tableFooterView = footview
                        
                        if isStartLoadingMore == false{
                             isStartLoadingMore = true
                            NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: Selector("delayLoadMoreData"), object: nil)
                            self.performSelector(#selector(HMAllOrdersViewController.loadMoreData), withObject: nil, afterDelay: 0.3)
                        }else{
                            return
                        }
                        
                    }
                } 
                
            }
        }
        
    }
    
    func loadMoreData(){
        autoreleasepool { () -> () in
            
            
            if isFromNotification == true {
                let dict = SHDataProvider.getDealerNoticeList(["type": notice_status,"dealer_id":SHDataProvider.getDealerID(),"page":"\(dCurrentPage+1)"])
                
                let ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
                
                SWUtils.RunOnMainThread({ () -> Void in
                    if let orderList = ary{
//                        self.aryList.removeAllObjects()
                        if orderList.count > 0 {
//                            self.isStartLoadingMore = false
                            self.aryList.addObjectsFromArray(orderList)
                            self.dCurrentPage+=1
                            if self.aryList.count >= self.dCurrentPage * 20 {
                                self.isStartLoadingMore = false
                            }else{
                                self.isStartLoadingMore = true
                                self.tvList.tableFooterView = nil;
                                return
                            }
                        }
                       
                    }else{
                        
                    }
//                    self.isStartLoadingMore = false
                    self.tvList.reloadData()
                     self.tvList.tableFooterView = nil;
                })
            }else{
                let strSearchText :NSString = searchBar.text!
                if strSearchText.length <= 0 {
                    let dict = SHDataProvider.getDealerOrderList(["order_status": order_status,"dealer_id":SHDataProvider.getDealerID(),"page":"\(self.dCurrentPage+1)"])
                    
                    let ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let orderList = ary{
//                            self.aryList.removeAllObjects()
                            if orderList.count > 0 {
                                
                                self.aryList.addObjectsFromArray(orderList)
                                self.dCurrentPage+=1
                                if self.aryList.count >= self.dCurrentPage * 20 {
                                    self.isStartLoadingMore = false
                                }else{
                                    self.isStartLoadingMore = true
                                     self.tvList.tableFooterView = nil;
                                    return
                                    
                                }
                            }
                        }else{
                            
                        }
                        self.tvList.reloadData()
                        self.tvList.tableFooterView = nil;
                    })

                }else{
                    let dict = SHDataProvider.getDealerOrderList(["search_no":searchBar.text!,"account_type":"1","order_status":order_status,"dealer_id":SHDataProvider.getDealerID(),"page":"\(dCurrentPage+1)"])
//                    var dict = SHDataProvider.getDealerOrderList(["order_status": order_status,"dealer_id":SHDataProvider.getDealerID(),"page":"\(dCurrentPage+1)"])
                    
                    let ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let orderList = ary{
//                            self.aryList.removeAllObjects()
                            if orderList.count > 0 {
                                
                                self.aryList.addObjectsFromArray(orderList)
                                self.dCurrentPage+=1
                                
                                if self.aryList.count >= self.dCurrentPage * 20 {
                                    self.isStartLoadingMore = false
                                }else{
                                    self.isStartLoadingMore = true
                                    self.tvList.tableFooterView = nil;
                                    return
                                }
                            }
                        }else{
                            
                        }
//                        self.isStartLoadingMore = false
                        self.tvList.reloadData()
                        self.tvList.tableFooterView = nil;

                    })

                }
                
            }
            
        }
    }
    
    override func navBack() {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func statusChanged(sender: UISegmentedControl){
        if sender.selectedSegmentIndex==0{
            if !notice_status.hasPrefix("0") {
                notice_status = "0"
                refresh()
            }
        }else if sender.selectedSegmentIndex==1{
            if !notice_status.hasPrefix("1") {
                notice_status = "1"
                refresh()
            }
        }else{
            if !notice_status.hasPrefix("2"){
                notice_status = "2"
                refresh()
            }
        }
    }
    
    func showSelectedTakeCarPerson() {
      btnHide.hidden = false
      vMarkPerson.hidden = false
      tvListPerson.hidden = false
       NSThread .detachNewThreadSelector(#selector(HMAllOrdersViewController.loadGetCarPersonListData), toTarget: self, withObject: nil)
//        vSelectPerson.hidden = false
    }
    
    func hiddenTakeCarPerson() {
        btnHide.hidden = true
        vMarkPerson.hidden = true
        tvListPerson.hidden = true
//        vSelectPerson.hidden = true
        vMark = nil
        btnHidePusPay = nil
        vPay = nil
        var myDelegate:AppDelegate
        myDelegate = (UIApplication.sharedApplication().delegate as? AppDelegate)!
        
        vMark = UIView(frame: CGRectMake(0,0,1024,768))
        vMark.backgroundColor = UIColor.blackColor()
        vMark.alpha = 0.5
        myDelegate.window?.addSubview(vMark)
        
        
        btnHidePusPay = UIButton (type: UIButtonType.Custom)
        btnHidePusPay.frame = CGRectMake(0, 0, 1024, 768)
        btnHidePusPay.backgroundColor = UIColor.clearColor()
        myDelegate.window?.addSubview(btnHidePusPay)
        btnHidePusPay.addTarget(self, action: #selector(HMAllOrdersViewController.dismissShowViews), forControlEvents: .TouchUpInside)
//        btnHidePusPay.hidden = true
        
        vPay = UIView(frame: CGRectMake(360+15,164,1024-360-30,360))
        vPay.backgroundColor = UIColor.whiteColor()
        vPay.layer.cornerRadius = 8
        myDelegate.window?.addSubview(vPay)
        
        
        let lblPayMoney = UILabel.create(CGRectMake(20,30,300,25), font: UIFont.systemFontOfSize(20), textColor: UIColor.blackColor())
        lblPayMoney.text = "消费金额：________________元"
        vPay.addSubview(lblPayMoney)
        
        
        tfPrice = UITextField.init(frame: CGRectMake(120, 10, 140, 55))
        tfPrice.keyboardType = .PhonePad
        tfPrice.delegate = self;
        tfPrice.backgroundColor = UIColor.clearColor()
        tfPrice.placeholder = "0.00"
        vPay.addSubview(tfPrice)
        
      
        
        let lblPayDetail = UILabel.create(CGRectMake(20,90,100,25), font: UIFont.systemFontOfSize(20), textColor: UIColor.blackColor())
        lblPayDetail.text = "费用清单："
        vPay.addSubview(lblPayDetail)

        for index in 0  ..< 3 {
            
            let newIndex  = index * 150
            
            imgvPhoto = UIImageView.init(frame: CGRectMake(140.0 + (CGFloat)(newIndex) , 95, 140, 140))
            imgvPhoto.image = UIImage(named: "add_phont_icon")
//            imgvPhoto.backgroundColor = UIColor.grayColor()
            imgvPhoto.userInteractionEnabled = true
            imgvPhoto.tag = 100+index
            if imgvPhoto.tag == 100{
                imgvPhoto.hidden = false
            }else{
                imgvPhoto.hidden = true
            }
            vPay .addSubview(imgvPhoto)
            
            let btn = UIButton(type: UIButtonType.Custom)
            btn.frame = imgvPhoto.frame
            btn.backgroundColor = UIColor.clearColor()
            vPay.addSubview(btn)
            btn.tag = index
            btn.addTarget(self, action: #selector(HMAllOrdersViewController.showImage(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        }
        
        let imgvPayLine = UIImageView.init(frame: CGRectMake(0, 289, vPay.frame.size.width, 1))
        imgvPayLine.backgroundColor = UIColor.grayColor()
        vPay.addSubview(imgvPayLine);
        
        let btnAdd = UIButton(type: UIButtonType.Custom)
        btnAdd.frame = CGRectMake(140 + (CGFloat)(150*(0)), 95, 140, 140)
        btnAdd.setBackgroundImage(UIImage(named: "add_phont_icon"), forState: UIControlState.Normal)
        vPay.addSubview(btnAdd)
        btnAdd.tag = 1000
        btnAdd.addTarget(self, action: #selector(HMAllOrdersViewController.selectedPhotoClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        
        
        let btnCommit = UIButton(type: UIButtonType.Custom)
        btnCommit.frame = CGRectMake(180, 360-40-15, 240, 40)
        btnCommit.backgroundColor = UIColor(red: 0.17, green: 0.52, blue: 0.80, alpha: 1)
        btnCommit.setTitle("确定", forState: UIControlState.Normal)
        btnCommit.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        vPay.addSubview(btnCommit)
        btnCommit.addTarget(self, action: #selector(HMAllOrdersViewController.btnCommitClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    
    // MARK: - UITableView Delegate & Data Source
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if tableView == tvList {
            let identifier = "OrderCell"
            var cell = tableView.dequeueReusableCellWithIdentifier(identifier) as UITableViewCell!
            
            if cell==nil{
                cell = UITableViewCell(style: .Default, reuseIdentifier: identifier)
                cell.contentView.layer.borderWidth = 0.5
                cell.contentView.layer.borderColor = UIColor(red: 0.82, green: 0.84, blue: 0.86, alpha: 1).CGColor
                cell.contentView.backgroundColor = UIColor(red: 0.97, green: 0.98, blue: 0.99, alpha: 1)
                cell.selectionStyle = .None
                
                var lbl: UILabel = UILabel.create(CGRectMake(320-160, 15, 150, 18), font: UIFont.systemFontOfSize(13), textColor: UIColor.grayColor())
                lbl.textAlignment = .Right
                lbl.tag = 100
                cell.contentView.addSubview(lbl)
                
                lbl = UILabel.create(CGRectMake(20, 70, 250, 16), font: UIFont.systemFontOfSize(15), textColor: UIColor.grayColor())
                lbl.tag = 101
                cell.contentView.addSubview(lbl)
                
                lbl = UILabel.create(CGRectMake(20, 95, 250, 16), font: UIFont.systemFontOfSize(15), textColor: UIColor.grayColor())
                lbl.tag = 102
                cell.contentView.addSubview(lbl)
                
                lbl = UILabel.create(CGRectMake(20, 45, 250, 16), font: UIFont.systemFontOfSize(15), textColor: UIColor.grayColor())
                lbl.tag = 104
                cell.contentView.addSubview(lbl)
                
                lbl = UILabel.create(CGRectMake(20, 120, 250, 16), font: UIFont.systemFontOfSize(15), textColor: UIColor.grayColor())
                lbl.tag = 105
                lbl.hidden = true
                cell.contentView.addSubview(lbl)
                
                lbl = UILabel.create(CGRectMake(20, 15, 100, 18), font: UIFont.systemFontOfSize(15), textColor: UIColor.grayColor())
                lbl.tag = 103
//                lbl.textAlignment = .Center
                cell.contentView.addSubview(lbl)
                
                let line = UIView(frame: CGRectMake(0, 124.5, 320, 0.5))
                if isFromNotification == true{
                    line.frame = CGRectMake(0, 124.5, 320, 0.5)
                }else{
                    line.frame = CGRectMake(0, 149.5, 320, 0.5)
                }
                
                line.backgroundColor = UIColor(white: 0.88, alpha: 1)
                cell.contentView.addSubview(line)
                
                let circle = UIView(frame: CGRectMake(0, 0, 8, 8))
                circle.clipsToBounds = true
                circle.layer.cornerRadius = 4
                circle.backgroundColor = UIColor.whiteColor()
                circle.tag = 200
                cell.contentView.addSubview(circle)
                circle.center = CGPointMake(345-40, 62.5)
            }
            
            let lblName = cell.contentView.viewWithTag(100) as! UILabel!
            let lblPhone = cell.contentView.viewWithTag(101) as! UILabel!
            let lblOrderTime = cell.contentView.viewWithTag(102) as! UILabel!
            let lblOrderType = cell.contentView.viewWithTag(103) as! UILabel!
            let lblOrderNo = cell.contentView.viewWithTag(104) as! UILabel!
            let lblStartTime = cell.contentView.viewWithTag(105) as! UILabel!
            let circle = cell.contentView.viewWithTag(200)!
            
            if isFromNotification == true{
                lblStartTime.hidden = true
                let info = aryList[indexPath.row]
                print(info)
                let orderInfo = info.objectForKey("order_info")
//                 let orderInfo = aryList[indexPath.row]
                lblName.text = info.objectForKey("create_at") as! String?

//                lblName.text = orderInfo!.objectForKey("nickname") as! String?
                lblOrderTime.text = "预约时间：".stringByAppendingString(orderInfo!.objectForKey("order_time") as! String!)
                
                if let orderType = orderInfo!.objectForKey("order_type")?.intValue{
                    lblOrderType.hidden = false
                    if 1==orderType{
                        lblOrderType.text = "保养"
//                        lblOrderType.backgroundColor = UIColor(red: 0.02, green: 0.64, blue: 0.95, alpha: 1)
                    }else if 2==orderType{
                        lblOrderType.text = "维修"
//                        lblOrderType.backgroundColor = UIColor(red: 0.02, green: 0.64, blue: 0.95, alpha: 1)
                    }else{
                        lblOrderType.text = "保养和维修"
//                        lblOrderType.backgroundColor = UIColor(red: 0.95, green: 0.61, blue: 0.08, alpha: 1)
                    }
                }else{
                    lblOrderType.hidden = true
                }
                
                if let checkNo = orderInfo!.objectForKey("check_no") as! String!{
                    lblOrderNo.text = "预约单号：\(checkNo)"
                }else{
                    lblOrderNo.text = "预约单号：";
                }
                
                if let phone = orderInfo!.objectForKey("order_phone") as! String!{
                    lblPhone.text = "联系电话：\(phone)"
                }else if let phone = orderInfo!.objectForKey("phone") as! String!{
                    lblPhone.text = "联系电话：\(phone)"
                }else{
                    lblPhone.text = "联系电话："
                }
                
                if IndexNoticeSelected == indexPath.row && isSelectedNotice == true{
                    cell.contentView.backgroundColor = UIColor.lightGrayColor()
                    lblOrderNo.textColor = UIColor.whiteColor()
                    lblPhone.textColor = UIColor.whiteColor()
                    lblOrderTime.textColor = UIColor.whiteColor()
                    lblName.textColor = UIColor.whiteColor()
                    lblOrderType.textColor = UIColor.whiteColor()

                }else{
                    cell.contentView.backgroundColor = UIColor.whiteColor()
                    lblOrderNo.textColor = UIColor.grayColor()
                    lblPhone.textColor = UIColor.grayColor()
                    lblOrderTime.textColor = UIColor.grayColor()
                    lblName.textColor = UIColor.grayColor()
                    lblOrderType.textColor = UIColor.grayColor()

                }


                
                circle.hidden = false
//                if let order_status = orderInfo!.objectForKey("order_status")?.integerValue as Int!{
//                    if 1 == order_status{
//                        circle.backgroundColor = UIColor(red: 0.99, green: 0.84, blue: 0.19, alpha: 1)
//                    }else if 2 == order_status{
//                        circle.backgroundColor = UIColor.redColor()
//                    }else{
//                        circle.backgroundColor = UIColor.greenColor()
//                    }
                    
//                }
                

            }else{
                let orderInfo = aryList[indexPath.row]
                 lblStartTime.hidden = false
                lblName.text = orderInfo.objectForKey("nickname") as! String?
                lblOrderTime.text = "预约时间：".stringByAppendingString(orderInfo.objectForKey("order_time") as! String!)
                lblStartTime.text = "创建时间：".stringByAppendingString(orderInfo.objectForKey("create_time") as! String!)
                
                if let orderType = orderInfo.objectForKey("order_type")?.intValue{
                    lblOrderType.hidden = false
                    if 1==orderType{
                        lblOrderType.text = "保养"
//                        lblOrderType.backgroundColor = UIColor(red: 0.02, green: 0.64, blue: 0.95, alpha: 1)
                    }else if 2==orderType{
                        lblOrderType.text = "维修"
//                        lblOrderType.backgroundColor = UIColor(red: 0.02, green: 0.64, blue: 0.95, alpha: 1)
                    }else{
                        lblOrderType.text = "维修和保养"
//                        lblOrderType.backgroundColor = UIColor(red: 0.95, green: 0.61, blue: 0.08, alpha: 1)
                    }
                }else{
                    lblOrderType.hidden = true
                }
                
                if let checkNo = orderInfo.objectForKey("check_no") as! String!{
                    lblOrderNo.text = "预约单号：\(checkNo)"
                }else{
                    lblOrderNo.text = "预约单号：";
                }
                
                if let phone = orderInfo.objectForKey("order_phone") as! String!{
                    lblPhone.text = "联系电话：\(phone)"
                }else if let phone = orderInfo.objectForKey("phone") as! String!{
                    lblPhone.text = "联系电话：\(phone)"
                }else{
                    lblPhone.text = "联系电话："
                }
                
                if orderInfo===selectedOrder{
                    cell.contentView.backgroundColor = UIColor.lightGrayColor()
                    lblOrderNo.textColor = UIColor.whiteColor()
                    lblPhone.textColor = UIColor.whiteColor()
                    lblOrderTime.textColor = UIColor.whiteColor()
                    lblName.textColor = UIColor.whiteColor()
                }else{
                    cell.contentView.backgroundColor = UIColor.whiteColor()
                    lblOrderNo.textColor = UIColor.grayColor()
                    lblPhone.textColor = UIColor.grayColor()
                    lblOrderTime.textColor = UIColor.grayColor()
                    lblName.textColor = UIColor.grayColor()
                }
                
                circle.hidden = false
                
                if let dealer_handle_type = orderInfo.objectForKey("dealer_handle_type")?.integerValue as Int!{
                    if 1 == dealer_handle_type{
                        circle.backgroundColor = UIColor(red: 0.99, green: 0.84, blue: 0.19, alpha: 1)
                    }else if 2 == dealer_handle_type{
                        circle.backgroundColor = UIColor.redColor()
                    }else{
                        circle.backgroundColor = UIColor.greenColor()
                    }
                    
                }
                
                if let order_status = orderInfo.objectForKey("order_status")?.integerValue as Int!{
                    if 1 == order_status{
                        lblName.text  = "已发起"
                    }else if 2 == order_status{
                        lblName.text  = "已拒绝"
                    }else if 3 == order_status{
                        lblName.text  = "已接受"
                    }else if 4 == order_status{
                        if let back_type = orderInfo.objectForKey("back_type")?.integerValue as Int! {
                            if back_type == 1 {
                                lblName.text = "待评价"
                                
                            }else{
                                lblName.text = "服务中"
                            }
                        }
                        
                    }else if 5 == order_status{
                        lblName.text  = "已评价"
                    }else if 6 == order_status{
                        lblName.text  = "已接受"
                    }else if 7 == order_status{
                        lblName.text  = "服务中"
                    }else if 8 == order_status{
                        lblName.text  = "服务中"
                    }else if 9 == order_status{
                        if  let pick_type = orderInfo.objectForKey("pick_type")?.integerValue as Int!{
                            if pick_type == 1{
                                lblName.text  = "待付款"
                            }else{
                                lblName.text  = "服务中"
                                
                            }
                        }
                        
                    }else if 10 == order_status{
                        lblName.text  = "待付款"
                    }else if 11 == order_status{
                        if let back_type = orderInfo.objectForKey("back_type")?.integerValue as Int! {
                            if back_type == 1 {
                                lblName.text = "待评价"
                                
                            }else{
                                lblName.text = "服务中"
                            }
                        }
                    }else if 12 == order_status{
                        lblName.text  = "待评价"
                    }else if 13 == order_status{
                        lblName.text  = "已取消"
                    }else if 14 == order_status{
                        lblName.text  = "待确认"
                    }else{
                        lblName.text  = "已发起"
                    }

                }
 
            }
            
            return cell

        }
        
        
        let identifierTake = "takeIdentifier"
        var cell = tableView.dequeueReusableCellWithIdentifier(identifierTake) as UITableViewCell!
        
        if cell==nil{
            cell = UITableViewCell(style: .Default, reuseIdentifier: identifierTake)
            cell.contentView.layer.borderWidth = 0.5
            cell.contentView.layer.borderColor = UIColor(red: 0.82, green: 0.84, blue: 0.86, alpha: 1).CGColor
            cell.contentView.backgroundColor = UIColor(red: 0.97, green: 0.98, blue: 0.99, alpha: 1)
            cell.selectionStyle = .None
            
            
            var imgv = SWImageView(frame: CGRectMake(50, 20, 60, 60))
            imgv.backgroundColor = UIColor.whiteColor()
            imgv.layer.cornerRadius = 30.0
            imgv.clipsToBounds = true
            imgv.tag = 1000
            imgv.delegate = self
            cell.contentView.addSubview(imgv)
            
            imgv = SWImageView(frame: CGRectMake(15, 40, 20, 20))
            imgv.image = UIImage(named: "normal")
            imgv.layer.cornerRadius = 3.0
            imgv.tag = 1005
            imgv.delegate = self
            cell.contentView.addSubview(imgv)
            
            var lbl = UILabel.create(CGRectMake(120, 20, 230, 18), font: UIFont.systemFontOfSize(18), textColor: UIColor.blackColor())
            lbl.tag = 1001
            cell.contentView.addSubview(lbl)
            
            lbl = UILabel.create(CGRectMake(120, 45, 230, 18), font: UIFont.systemFontOfSize(15), textColor: UIColor.grayColor())
            lbl.tag = 1002
            cell.contentView.addSubview(lbl)
            
            lbl = UILabel.create(CGRectMake(120, 70, 230, 18), font: UIFont.systemFontOfSize(15), textColor: UIColor.grayColor())
            lbl.tag = 1003
            cell.contentView.addSubview(lbl)
        }
        
        
        
        let lblPersonName = cell.contentView.viewWithTag(1001) as! UILabel!
        let lblPersonPhone = cell.contentView.viewWithTag(1002) as! UILabel!
        let lblPersonNumber = cell.contentView.viewWithTag(1003) as! UILabel!
        let imgvPersonPortrait = cell.contentView.viewWithTag(1000) as! SWImageView!
        let imgvPersonSelected = cell.contentView.viewWithTag(1005) as! SWImageView!
        
        
//        lblName.text = orderInfo.objectForKey("nickname") as! String?
//        lblOrderTime.text = "预约时间：".stringByAppendingString(orderInfo.objectForKey("order_time") as! String!)
        let personInfo = aryPersonList[indexPath.row]
        lblPersonName.text = personInfo.objectForKey("name") as! String?
        lblPersonPhone.text = personInfo.objectForKey("telephone") as! String?
        lblPersonNumber.text = personInfo.objectForKey("work_no") as! String?
        
        imgvPersonPortrait.image = UIImage(named: "portrait")
//        imgvPersonPortrait.loadURL(aryPersonList[indexPath.row].objectForKey("head_uri") as? String)
        
//        imgvPersonPortrait.imageWithUrl(aryPersonList[indexPath.row].objectForKey("head_uri") as? String, placeHolderImage: UIImage(named: "portrait"))
        
        if IndexSelected == indexPath.row && isSelectedPerson == true{
            imgvPersonSelected.image = UIImage(named: "seleted")
            cell.contentView.backgroundColor = UIColor(red: 0.14, green: 0.50, blue: 0.78, alpha: 1)
            lblPersonName.textColor = UIColor.whiteColor()
            lblPersonPhone.textColor = UIColor.whiteColor()
            lblPersonNumber.textColor = UIColor.whiteColor()
        }else{
            imgvPersonSelected.image = UIImage(named: "normal")
            cell.contentView.backgroundColor = UIColor.whiteColor()
//            cell.selected = false
            lblPersonName.textColor = UIColor.blackColor()
            lblPersonPhone.textColor = UIColor.grayColor()
            lblPersonNumber.textColor = UIColor.grayColor()
        }
        
        
        
        cell.selectionStyle = UITableViewCellSelectionStyle.Blue
        return cell
        
        
    
}
    
    func downimage(url : NSString){
        
        let urlStr:NSString  = url
        
        let  request:NSURLRequest = NSURLRequest(URL: NSURL(string: urlStr as String)!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval:2.0)
        
        NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue()) { (response, data, error) ->Void in
            
            let  path:NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory,NSSearchPathDomainMask.UserDomainMask,true)[0];
            
            let  cachepaht = path.stringByAppendingPathComponent("test.png")
            
            data?.writeToFile(cachepaht, atomically:true);
        }
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if tableView == tvList{
            if isFromNotification == true{
                return 125
            }
            return 150.0
        }
        return 100.0
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        return aryList.count
        
        if tableView == tvList{
            return aryList.count
        }
        return aryPersonList.count
    }
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        var v = UIView()
        if isFromNotification == true{
            v = UIView(frame: CGRectMake(0, 0, 320, 120))
            v.backgroundColor = UIColor.whiteColor()
            
            let vNavTitleBG = UIView(frame: CGRectMake(0, 0, 320, 50))
            vNavTitleBG.backgroundColor = UIColor(white: 0.94, alpha: 1)
            v.addSubview(vNavTitleBG)
            
            let lblNavTitle = UILabel(frame: CGRectMake(0, 0, 320, 50))
            lblNavTitle.text = strNavTitle as? String
            lblNavTitle.font = UIFont.systemFontOfSize(17)
            lblNavTitle.textAlignment = .Center
            lblNavTitle.textColor = UIColor(white: 0.30, alpha: 1)
            v.addSubview(lblNavTitle)
//            vNotificationDetail.str = strNavTitle
            
            let btnBack: UIButton = UIButton(frame: CGRectMake(0, 15, 40, 20))
            //        btnBack.clipsToBounds = true
            //        btnBack.layer.cornerRadius = 4
            //        btnBack.layer.borderWidth = 1
            //        btnBack.layer.borderColor = UIColor(white: 1, alpha: 0.5).CGColor
            
            btnBack.setImage(UIImage(named: "back"), forState: UIControlState.Normal)
            btnBack.addTarget(self, action: #selector(UIViewController.navBack), forControlEvents: .TouchUpInside)
            v.addSubview(btnBack)
            
            
            let seg = UISegmentedControl(items: ["全部","新预约","支付通知"])
            seg.frame = CGRectMake(20, 50 + 15, 280, 40)
            seg.center = CGPointMake(160, 50+35)
            seg.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFontOfSize(16)], forState: .Normal)
            v.addSubview(seg)
//            seg.selectedSegmentIndex = 2
            seg.addTarget(self, action: #selector(HMAllOrdersViewController.statusChanged(_:)), forControlEvents: .ValueChanged)
            
            if notice_status.hasPrefix("0"){
                seg.selectedSegmentIndex = 0
            }else if notice_status.hasPrefix("1"){
                seg.selectedSegmentIndex = 1
            }else if notice_status.hasPrefix("2"){
                seg.selectedSegmentIndex = 2
            }

        }else{
            v = UIView(frame: CGRectMake(0, 0, 320, 50))
            v.backgroundColor = UIColor.whiteColor()
            
            let vNavTitleBG = UIView(frame: CGRectMake(0, 0, 360, 50))
            vNavTitleBG.backgroundColor = UIColor(white: 0.94, alpha: 1)
            v.addSubview(vNavTitleBG)
            
            let lblNavTitle = UILabel(frame: CGRectMake(0, 0, 360, 50))
            lblNavTitle.text = strNavTitle as? String
            lblNavTitle.font = UIFont.systemFontOfSize(17)
            lblNavTitle.textAlignment = .Center
            lblNavTitle.textColor = UIColor(white: 0.30, alpha: 1)
            v.addSubview(lblNavTitle)
            vAllOrders.str = strNavTitle
            
            let btnBack: UIButton = UIButton(frame: CGRectMake(0, 15, 40, 20))
            //        btnBack.clipsToBounds = true
            //        btnBack.layer.cornerRadius = 4
            //        btnBack.layer.borderWidth = 1
            //        btnBack.layer.borderColor = UIColor(white: 1, alpha: 0.5).CGColor
            
            btnBack.setImage(UIImage(named: "back"), forState: UIControlState.Normal)
            btnBack.addTarget(self, action: #selector(UIViewController.navBack), forControlEvents: .TouchUpInside)
            v.addSubview(btnBack)
            
            
            if isFromSearchOrder == true{
                btnShowSearch = UIButton(frame: CGRectMake(270, 15, 40, 20))
                btnShowSearch.setImage(UIImage(named: "btn_down"), forState: UIControlState.Normal)
                btnShowSearch.setImage(UIImage(named: "up"), forState: UIControlState.Selected)
                btnShowSearch.addTarget(self, action: #selector(HMAllOrdersViewController.userSelectSearch(_:)), forControlEvents: .TouchUpInside)
                v.addSubview(btnShowSearch)
            }
            
 
        }
        
        return v
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if tableView == tvList{
            
            if isFromNotification == true{
                switch section{
                case 0:
                    return 120
                default:
                    return 0.0
                }

            }else{
                switch section{
                case 0:
                    return 50
                default:
                    return 0.0
                }

            }
        }
        
        return 0.0
    }
    
//    func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
//        
//        let vFooterPerson = UIView.init(frame: CGRectMake(0, 0, 270, 75))
//        vFooterPerson.backgroundColor = UIColor.whiteColor()
//        vFooterPerson.layer.shadowColor = UIColor.blackColor().CGColor
//        vFooterPerson.layer.shadowRadius = 1
//        vFooterPerson.layer.shadowOffset = CGSizeMake(-2, 0)
//        vFooterPerson.layer.shadowOpacity = 0.1
//        
//        let btnSelectedPerson  = UIButton(type: UIButtonType.Custom)
//        btnSelectedPerson.frame = CGRectMake(35, 15, 200, 45)
//        btnSelectedPerson.backgroundColor = UIColor(red: 0.14, green: 0.50, blue: 0.78, alpha: 1)
//        btnSelectedPerson.setTitle("确定", forState: UIControlState.Normal)
//        btnSelectedPerson.setTitleColor(UIColor.whiteColor(), forState: .Normal)
//        vFooterPerson.addSubview(btnSelectedPerson)
//        btnSelectedPerson.addTarget(self, action: "btnSelectedPersonClicked", forControlEvents: .TouchUpInside)
//        
//        return vFooterPerson
//    }
//    
//    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
//        if tableView == tvList{
//            return 0.0
//        }
//        return 75.0
//    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        if tableView == tvList{
            
            if isFromNotification == true {
//                let orderInfo: AnyObject = aryList[indexPath.row].objectForKey("order_info")!
                let orderInfo: AnyObject = aryList[indexPath.row]

//                vAllOrders.allOrdersInfo = orderInfo as? NSDictionary
                vNotificationDetail.orderNotificationInfo = orderInfo as? NSDictionary
                selectedOrder = orderInfo as? NSDictionary
//                vAllOrders.number = indexPath.row as? NSNumber
//                vAllOrders.isFromNotification = true
                IndexNoticeSelected = indexPath.row
                isSelectedNotice = true
                if vAllOrders != nil {
                    vAllOrders.hidden = true
                }
                
                vNotificationDetail.hidden = false
                tvList.reloadData()
            }else{
                let orderInfo: AnyObject = aryList[indexPath.row]
                vAllOrders.allOrdersInfo = orderInfo as? NSDictionary
//                vNotificationDetail.orderNotificationInfo = orderInfo as? NSDictionary
                selectedOrder = orderInfo as? NSDictionary
                vAllOrders.number = indexPath.row
                tvList.reloadData()
            }
            
        }else{
            dicSelectedPersonInfo = aryPersonList[indexPath.row] as? NSDictionary
            isSelectedPerson = true
            IndexSelected = indexPath.row
            tvListPerson.reloadData()
            
        }
        
    }
    
    //MARK: - MHOrderDetail Delegate
    func orderUpdated(order: NSDictionary?) {
        if let dict = order{
            let order_id = dict.objectForKey("order_id")?.intValue!
            for i in 0 ..< aryList.count{
                let oi = aryList[i].objectForKey("order_id")?.intValue!
                
                if order_id==oi{
                    aryList.replaceObjectAtIndex(i, withObject: dict)
                    break
                }
            }
            
            tvList.reloadData()
        }
    }
    
    //MARK: -显示搜索条件
    func userSelectSearch(sender:UIButton){
        print("显示搜索条件")
        sender.selected = true
        
        vMarkSearch.hidden = false
//        vSearchOrderView.hidden = false
        imgvSearchBG.hidden = false
        
    }
    //MARK: - MHAllOrders Delegate
    func allOrdesUpdated(order: NSDictionary?) {
        if let dict = order{
            let order_id = dict.objectForKey("order_id")?.intValue!
            for i in 0 ..< aryList.count{
                let oi = aryList[i].objectForKey("order_id")?.intValue!
                
                if order_id==oi{
                    aryList.replaceObjectAtIndex(i, withObject: dict)
                    break
                }
            }
            
            tvList.reloadData()
        }
    }
    
    func selectedPhotoClicked(sender: UIButton){
        let actionSheet = UIActionSheet()
        actionSheet.title = "选择要进行的操作"
        actionSheet.delegate = self
        actionSheet.addButtonWithTitle("相册")
        actionSheet.addButtonWithTitle("拍照")
        actionSheet.addButtonWithTitle("取消")
        //        var actionSheet = UIActionSheet(title: "选择要进行的操作", delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles:nil)
        //        actionSheet.addButtonWithTitle("注销")
//        actionSheet.showFromRect(CGRectMake(sender.frame.origin.x,sender.frame.origin.y,200, 300), inView:self.view, animated: true)
        actionSheet.showInView(self.view)
       
        
    }
    
    func showImage(sender: UIButton){
        
        
        
    }
    
    func btnCommitClicked(sender: UIButton){
        tfPrice.resignFirstResponder()
        vPay.hidden = true
        
        vMark.hidden = true
        strPrice  = self.tfPrice.text! as NSString

        if strPrice.length == 0 || strPrice.integerValue <= 0 {
            
             UIAlertView.show(nil, message: "请输入金额！", cancelButton: nil)
             return

        }else{
            self.endService()
        }
        
        
        
    }
  
    
    //服务完成
    func endService(){
        SWUtils.RunOnBackgroundThread { () -> Void in
            autoreleasepool({ () -> () in
                if let order_id = self.vAllOrders.allOrdersInfo?.objectForKey("order_id") as! String!{
                    let str = NSMutableString()
                    if self.aryPhotosURI.count != 0{
                        for i in 0 ..< self.aryPhotosURI.count{
                            
                            let key = self.aryPhotosURI[i]
                            str.appendString(key as! String)
                            str.appendString(",")
                            
                        }
                    }
  
                    
                    let dicParams = ["order_id" : order_id, "price" : self.strPrice, "photo_uris" : str]
                    let dict = SHDataProvider.endService(dicParams)
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let code = dict?.objectForKey("code")?.intValue{
                            if code==200{
                                UIAlertView.show(nil, message: "操作成功", cancelButton: nil)
                                let mut = NSMutableDictionary(dictionary: self.vAllOrders.allOrdersInfo!) as NSMutableDictionary
                                mut.setObject("4", forKey: "order_status")
                                
                                self.vAllOrders.allOrdersInfo = NSDictionary(dictionary: mut)
                            }else{
                                if let msg = dict?.objectForKey("message") as? String{
                                    UIAlertView.show(nil, message: msg, cancelButton: nil)
                                }else{
                                    UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                                }
                            }
                        }else{
                            UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                        }
                        
                        self.getNewOrderDetail()
//                        self.allOrdesUpdated(self.vAllOrders.allOrdersInfo)
                    })
                }
            })
        }
    }


    
    //获取最新订单详情
    func getNewOrderDetail(){
        SWUtils.RunOnBackgroundThread { () -> Void in
            autoreleasepool({ () -> () in
                if let order_id = self.vAllOrders.allOrdersInfo?.objectForKey("order_id") as! String!{
                    let dict = SHDataProvider.getOrderDetail(NSDictionary(object: order_id,forKey: "order_id"))
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let code = dict?.objectForKey("code")?.intValue{
                            if code==200{
                                let dic = NSDictionary(dictionary: (dict?.objectForKey("data"))! as! [NSObject : AnyObject])
                                self.vAllOrders.allOrdersInfo = dic
//                                self.allOrdesUpdated(self.vAllOrders.allOrdersInfo)
                                
                            }else{
                               
                            }
                        }else{
                            //                            UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                        }
                        
                        //                        self.updateAllOrdersInfo()
                    })
                }
            })
        }
        
    }
    
    // 输入框内容改变触发事件
    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
        print("过滤：(searchText)")
    }
    // 书签按钮触发事件
    func searchBarBookmarkButtonClicked(searchBar: UISearchBar) {
        print("搜索历史")
    }
    
    // 取消按钮触发事件
    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        print("取消搜索")
    }
    
    // 搜索触发事件
    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        print("开始搜索")
        searchBar.resignFirstResponder()
        
        self.loadData()
    }
    
    
    func searchStart(){
//        order_status = "0";
        let dict = SHDataProvider.getDealerOrderList(["search_no":searchBar.text!,"account_type":"1","order_status":order_status,"dealer_id":SHDataProvider.getDealerID()])
        
        //            var dict = SHDataProvider.getDealerOrderList(["dealer_id":SHDataProvider.getDealerID()])
        
        let ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
        
        SWUtils.RunOnMainThread({ () -> Void in
            if let orderList = ary{
                self.aryList.removeAllObjects()
                self.aryList = NSMutableArray(array: orderList)
                
                if orderList.count>0{
                    let formatter = NSDateFormatter()
                    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
                    let d = formatter.dateFromString(orderList[0].objectForKey("create_time") as! String)
                    if let dd = d{
                        NSUserDefaults.standardUserDefaults().setObject(dd, forKey: "LatestOrderTime")
                    }
                }
            }else{
                self.aryList.removeAllObjects()
            }
            
            self.tvList.reloadData()
            self.refreshController.endRefreshing()
            
            if self.aryList.count>0{
                self.tableView(self.tvList, didSelectRowAtIndexPath: NSIndexPath(forRow: 0, inSection: 0))
            }else{
                self.vDetail.orderInfo = nil
            }
            
            
        })

    }
    
    // MARK: - UIActionSheet Delegate
    func actionSheet(actionSheet: UIActionSheet, didDismissWithButtonIndex buttonIndex: Int) {
        imagePicker = nil
        if buttonIndex >=  0 {
            let buttonTitle = actionSheet.buttonTitleAtIndex(buttonIndex)
            
            if buttonTitle=="拍照"{
                if UIImagePickerController.isSourceTypeAvailable(.Camera){
                    imagePicker = UIImagePickerController()
                    imagePicker.delegate = self
                    imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
                    imagePicker.modalTransitionStyle = UIModalTransitionStyle.CoverVertical
                    imagePicker.supportedInterfaceOrientations()
                    imagePicker.allowsEditing = true
                    self.presentViewController(imagePicker, animated: true, completion: nil)
//                    pop = nil
//                    pop = UIPopoverController.init(contentViewController: imagePicker)
//                    pop.popoverContentSize = CGSizeMake(UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height)
//                    pop.presentPopoverFromRect(CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height), inView:self.view, permittedArrowDirections: .Any, animated: true)
                }
                
                
                
            }else if buttonTitle == "相册"{
                if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
                    imagePicker = UIImagePickerController()
                    imagePicker.delegate = self
                    imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
                    imagePicker.modalTransitionStyle = UIModalTransitionStyle.CoverVertical
                    imagePicker.allowsEditing = true
                    //            self.presentViewController(imagePicker, animated: true, completion: nil)
                    pop = nil
                    pop = UIPopoverController.init(contentViewController: imagePicker)
                    pop.popoverContentSize = CGSizeMake(500, 500)
                    
                    pop.presentPopoverFromRect(CGRectMake(0, 0, 500, 500), inView: self.view, permittedArrowDirections: .Any, animated: true)
                }
                
            }else{
                
            }

        }
        
    }
    
//    override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask{
//        //错误写法 return (UIInterfaceOrientationsMask.Portrait | UIInterfaceOrientationsMask.LandscapeLeft);
//        //上面会报错。。说是UIInterfaceOrientationsMask不能转成Bool
//        //google了一下，原来，，，应该这样写
//        return  [UIInterfaceOrientationMask.Portrait, UIInterfaceOrientationMask.PortraitUpsideDown]
//    }
   
    // MARK -UIImagePikerControllerDelegate
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        var imageToSave:UIImage
        //UIImagePickerControllerEditedImage,这个需要特别注意，根据需要获得不同的图片，此处这个参数代表得到编辑完的图片，还有其他函数QAQ被坑了一晚
        imageToSave = info[UIImagePickerControllerEditedImage] as! UIImage
        //获取到相机拍出来的视频，userImage为我view里的image view控件名称，自行更改
    
        //        imgvPhoto.image = image
                let imgdata = UIImageJPEGRepresentation(imageToSave, 0.05)
                let strImgHash = imgdata?.SHA1String() as String!
                let strHashPath = strImgHash?.imageCachePath() as String!
                imgdata?.writeToFile(strHashPath!, atomically: false)
        
                let token = ABQiniuUtils.uploadTokenOfFile(nil) as String!
                print("token :\(token)")
                QNUploadManager.sharedManager().putFile(strHashPath!, key: nil, token: token, complete: {
                    info ,key , resp in
        
                    print("status code :\(info.statusCode)")
                    if (info != nil) {
                        if info.statusCode == 200 {
                            //            var ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
                            let newResp :NSDictionary = resp
        
                            self.realkey = newResp.objectForKey("key") as! String!
                            self.aryPhotos.addObject(imageToSave)
                            self.aryPhotosURI.addObject(self.realkey!)
                            self.refreshButtons()
                        }
                    }
        
                }, option: nil)
                
                picker.dismissViewControllerAnimated(true, completion: (nil))
        
//         self.dismissViewControllerAnimated(true, completion: nil)
    }

    
//    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//       
//        
//        aryPhotos.addObject(image)
//        self.refreshButtons()
//        
//      
////        imgvPhoto.image = image
//        let imgdata = UIImageJPEGRepresentation(image, 0.1)
//        let strImgHash = imgdata?.SHA1String() as String!
//        let strHashPath = strImgHash?.imageCachePath() as String!
//        imgdata?.writeToFile(strHashPath!, atomically: false)
//        
//        let token = ABQiniuUtils.uploadTokenOfFile("") as String!
//        
//        QNUploadManager.sharedManager().putFile(strHashPath!, key: nil, token: token, complete: {
//            info ,key , resp in
//            
//            print("status code :\(info.statusCode)")
//            if (info != nil) {
//                if info.statusCode == 200 {
//                    //            var ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
//                    var newResp :NSDictionary = resp
//                    
//                    self.realkey = newResp.objectForKey("key") as! String!
//                }
//            }
//
//        }, option: nil)
//        
//        picker.dismissViewControllerAnimated(true, completion: nil)
//        
//    }
    
    func imagePickerControllerDidCancel(picker:UIImagePickerController)    {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func refreshButtons(){
//        imgvPhoto.image = aryPhotos[0] as! UIImage
        photoCount += 1
         let imgv1 = vPay.viewWithTag(100) as! UIImageView
         let imgv2 = vPay.viewWithTag(101) as! UIImageView
         let imgv3 = vPay.viewWithTag(102) as! UIImageView
        let btnAdd = vPay.viewWithTag(1000) as! UIButton

        if photoCount == 1{
            imgv1.image = self.aryPhotos[0] as? UIImage
            btnAdd.frame =  CGRectMake(140 + (CGFloat)(150*(photoCount)), 95, 140, 140)
            btnAdd.hidden = false
        }else if photoCount == 2{
            imgv2.image = (self.aryPhotos[1] as! UIImage)
            imgv2.hidden = false
            btnAdd.frame =  CGRectMake(140 + (CGFloat)(150*(photoCount)), 95, 140, 140)
            btnAdd.hidden = false
        
        }else if photoCount == 3{
            imgv3.image = self.aryPhotos[2] as? UIImage
            imgv3.hidden = false
            btnAdd.frame =  CGRectMake(140 + (CGFloat)(150*(photoCount)), 95, 140, 140)
            btnAdd.hidden = true
        }else if photoCount > 3 {
            btnAdd.hidden = true
        }
       
        
        
        
        
        
        
        
        
        
        
        
        
        
    }
    
    
    //MARK: - MHOrderDetailNotification Delegate
    func orderNotificationUpdated(order: NSDictionary?) {
        if let dict = order{
            let order_id = dict.objectForKey("order_id")?.intValue!
            for i in 0 ..< aryList.count{
                let oi = aryList[i].objectForKey("order_id")?.intValue!
                
                if order_id==oi{
                    aryList.replaceObjectAtIndex(i, withObject: dict)
                    break
                }
            }
            
            tvList.reloadData()
        }
    }
    
    func showSelectedView(dic: NSDictionary?) {
        vNotificationDetail.hidden = true
        self.createOrderDetailView()
        vAllOrders.allOrdersInfo = dic
//        vAllOrders.hidden = false
    }
    
    
    func thePreviousStepClick(number: NSNumber?){
        
        
        if self.aryList.count>0{
            
            if number != 0 {
                self.tableView(self.tvList, didSelectRowAtIndexPath: NSIndexPath(forRow: ((Int)(number!) - 1), inSection: 0))
            }else{
                self.tableView(self.tvList, didSelectRowAtIndexPath: NSIndexPath(forRow: 0, inSection: 0))

            }
            
        }else{
            self.vDetail.orderInfo = nil
        }
    }
    func theNectStepClick(number:NSNumber?){
        if self.aryList.count>0{
            
            let index = (Int)(number!)
            
            if index >= aryList.count-1{
                self.tableView(self.tvList, didSelectRowAtIndexPath: NSIndexPath(forRow: aryList.count-1, inSection: 0))
            }else{
                self.tableView(self.tvList, didSelectRowAtIndexPath: NSIndexPath(forRow: ((Int)(number!) + 1), inSection: 0))
            }
            
        }else{
            self.vDetail.orderInfo = nil
        }
    }
    
    func hideOrderDetailView(number:NSNumber?){
        vAllOrders.hidden = true
        vNotificationDetail.hidden = false
    }
    
    //  MARK: - SWImageView Delegate
    func swImageViewLoadFinished(imgv: SWImageView) {
        
    }
    
    
   //获取取车员列表
    func loadGetCarPersonListData(){
        autoreleasepool { () -> () in
            dCurrentPage = 1;
            
            let dict = SHDataProvider.getDealerPersonList(["dealer_id":SHDataProvider.getDealerID()])
            
            print(dict)
            
            let ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
            
            SWUtils.RunOnMainThread({ () -> Void in
                if let personList = ary{
                    self.aryPersonList.removeAllObjects()
                    self.aryPersonList = NSMutableArray(array: personList)
                    
                    if personList.count>0{
//                        var formatter = NSDateFormatter()
//                        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
//                        var d = formatter.dateFromString(personList[0].objectForKey("create_time") as! String)
//                        if let dd = d{
//                            NSUserDefaults.standardUserDefaults().setObject(dd, forKey: "LatestOrderTime")
//                        }
                    }
                }else{
                    self.aryPersonList.removeAllObjects()
                }
                
                self.tvListPerson.reloadData()
//                self.refreshController.endRefreshing()
//                
//                if  self.aryPersonList.count>0{
//                    self.tableView(self.tvListPerson, didSelectRowAtIndexPath: NSIndexPath(forRow: 0, inSection: 0))
//                }else{
//                    self.vAllOrders.allOrdersInfo = nil
//                }
                
                
            })
        }
    }
    
  
    
    //选取取车员
    func selectedGetCarPerson(){
        autoreleasepool { () -> () in
            
//            let getCarID = vAllOrders.allOrdersInfo?.objectForKey("get_car_id")
            let work_no = dicSelectedPersonInfo!.objectForKey("work_no")
            let order_id = vAllOrders.allOrdersInfo?.objectForKey("order_id")
            let dict = SHDataProvider.shopSelectedGetCarPerson(["work_no":work_no!,"order_id":order_id!])
   
            SWUtils.RunOnMainThread({ () -> Void in
                let code = (dict!.objectForKey("code") as! NSNumber).integerValue
                NSLog("response code:%d",code)
                
                if code == 200 {
                    UIAlertView.show(nil, message: "操作成功", cancelButton: nil)
                    let mut = NSMutableDictionary(dictionary: self.vAllOrders.allOrdersInfo!) as NSMutableDictionary
                    mut.setObject("6", forKey: "order_status")
                    
                    self.vAllOrders.allOrdersInfo = NSDictionary(dictionary: mut)
                    
                }else{
                    UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                }
                
                self.allOrdesUpdated(self.vAllOrders.allOrdersInfo)
                
            })
        }
    }
    
    //选取送车员
    func selectedSendCarPerson(){
        autoreleasepool { () -> () in
            //\\
//            let sendCarID = vAllOrders.allOrdersInfo?.objectForKey("send_car_id")
            let work_no = dicSelectedPersonInfo!.objectForKey("work_no")
            let order_id = vAllOrders.allOrdersInfo?.objectForKey("order_id")

            let dict = SHDataProvider.shopSelectedSendCarPerson(["order_id":order_id!,"work_no":work_no!])
//            var ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
            
            SWUtils.RunOnMainThread({ () -> Void in
                let code = (dict!.objectForKey("code") as! NSNumber).integerValue
                NSLog("response code:%d",code)
                
                if code == 200 {
                    UIAlertView.show(nil, message: "操作成功", cancelButton: nil)
                    let mut = NSMutableDictionary(dictionary: self.vAllOrders.allOrdersInfo!) as NSMutableDictionary
                    mut.setObject("6", forKey: "order_status")
                    
                    self.vAllOrders.allOrdersInfo = NSDictionary(dictionary: mut)
                    
                }else{
                    UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                }
                
                self.allOrdesUpdated(self.vAllOrders.allOrdersInfo)
                
                
            })
        }
    }
    
    
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        if string == "0" || string == "1" || string == "2" || string == "3" || string == "4" || string == "5" || string == "6" || string == "7" || string == "8" || string == "9" || string == "" {
            return true
        }
        
        return false

    }
    
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        searchBar.resignFirstResponder()
    }

    

}
